package com.xiaozhen.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaozhen.blog.entity.Comment;
import com.xiaozhen.blog.entity.User;
import com.xiaozhen.blog.mapper.CommentMapper;
import com.xiaozhen.blog.service.CommentService;
import com.xiaozhen.blog.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @create 2023-04-27 19:48
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private UserService userService;

    /**
     * 保存评论信息
     *
     * @param comment
     * @return
     */
    @Override
    public Comment saveComment(Comment comment) {
        if (comment.getUserId() == 13) {
            comment.setAdminComment(1L);
        }
        commentMapper.insert(comment);
        return comment;
    }

    /**
     * 通过博客 id 获取评论列表
     *
     * @return
     */
    @Override
    public List<Comment> listCommentByBlogId(Long blogId) {
        // 条件查询
        LambdaQueryWrapper<Comment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Comment::getBlogId, blogId)
                .eq(Comment::getParentCommentId, -1)
                .orderByDesc(Comment::getCreateTime);
        // 获取一级列表
        List<Comment> comments = commentMapper.selectList(wrapper);
        // 后面要把 comments 中的 nickname、avatar、email 给覆盖了
        // 遍历一级列表
        for (Comment comment : comments) {
            // 可以在这里覆盖 comments
            // 通过评论的用户 id 获取用户信息
            User commentUser = userService.getById(comment.getUserId());
            comment.setNickname(commentUser.getNickname());
            comment.setAvatar(commentUser.getHeaderUrl());
            comment.setEmail(commentUser.getEmail());
            // 查询该评论的子评论（回复）
            LambdaQueryWrapper<Comment> replyWrapper = new LambdaQueryWrapper<>();
            replyWrapper.eq(Comment::getParentCommentId, comment.getId());
            List<Comment> replyCommentList = commentMapper.selectList(replyWrapper);

            // 遍历子评论（回复）列表
            for (Comment replyComment : replyCommentList) {
                User replyUser = userService.getById(replyComment.getUserId());
                replyComment.setNickname(replyUser.getNickname());
                replyComment.setAvatar(replyUser.getHeaderUrl());
                replyComment.setEmail(replyUser.getEmail());
                Comment parentComment = commentMapper.selectById(replyComment.getParentCommentId());
                replyComment.setParentNickname(parentComment.getNickname());
            }

            // 初始化子评论集合
            comment.setReplyComments(replyCommentList);
        }

        List<Comment> commentList = eachComment(comments);

        return commentList;
    }


    private List<Comment> eachComment(List<Comment> comments) {
        List<Comment> commentList = new ArrayList<>();
        for (Comment comment : comments) {
            Comment c = new Comment();
            BeanUtils.copyProperties(comment, c);
            commentList.add(c);
        }
        // 合并评论的
        combineChildren(commentList);
        return commentList;
    }


    /**
     * 合并评论的
     *
     * @param comments root根节点，blog 不为空的对象集合
     */
    private void combineChildren(List<Comment> comments) {
        for (Comment comment : comments) {
            List<Comment> replys = comment.getReplyComments();
            for (Comment reply : replys) {
                // 循环迭代，找出子代，存放在 tempReplys 中
                LambdaQueryWrapper<Comment> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(Comment::getParentCommentId, reply.getId());
                List<Comment> replyReplyList = commentMapper.selectList(wrapper1);
                for (Comment replyReply : replyReplyList) {
                    User replyReplyUser = userService.getById(replyReply.getUserId());
                    replyReply.setNickname(replyReplyUser.getNickname());
                    replyReply.setAvatar(replyReplyUser.getHeaderUrl());
                    replyReply.setEmail(replyReplyUser.getEmail());
                    Comment parentReply = commentMapper.selectById(replyReply.getParentCommentId());
                    replyReply.setParentNickname(parentReply.getNickname());
                }
                reply.setReplyComments(replyReplyList);
                recursively(reply);
            }
            // 修改顶级节点的reply集合为迭代处理后的集合
            comment.setReplyComments(tempReplys);
            // 清除临时存放区
            tempReplys = new ArrayList<>();
        }
    }

    // 存放迭代找出所有子代的集合
    private List<Comment> tempReplys = new ArrayList<>();

    /**
     * 递归迭代
     *
     * @param comment
     */
    private void recursively(Comment comment) {
        System.out.println("存放在 tempReplys 集合的评论数据 ==》" + comment.toString());
        // 顶节点添加到临时存放集合
        tempReplys.add(comment);

        if (comment.getReplyComments().size() > 0) {
            // 如果评论数据的子代集合大于 0，获取子代集合
            List<Comment> replys = comment.getReplyComments();
            // 遍历子代集合
            for (Comment reply : replys) {
                tempReplys.add(reply);
                if (reply.getReplyComments().size() > 0) {
                    // 如果子代的子代集合大于 0
                    recursively(reply);
                }
            }
        }
    }
}
